package com.example.consumer.controller;

import com.example.grpc.product.*;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 26891
 */
@RestController
@RequestMapping("/api/products")
public class ProductController {

    @GrpcClient("product-service")
    @Resource
    private ProductServiceGrpc.ProductServiceBlockingStub productServiceBlockingStub;


    @GetMapping("/{id}")
    public ResponseEntity<Product> getProduct(@PathVariable Long id) {
        GetProductRequest request = GetProductRequest.newBuilder().setId(id).build();
        GetProductResponse response = productServiceBlockingStub.getProduct(request);
        return ResponseEntity.ok(response.getProduct());
    }

    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody CreateProductRequestDto requestDto) {
        CreateProductRequest request = CreateProductRequest.newBuilder()
                .setName(requestDto.getName())
                .setDescription(requestDto.getDescription())
                .setPrice(requestDto.getPrice())
                .setQuantity(requestDto.getQuantity())
                .build();
        
        CreateProductResponse response = productServiceBlockingStub.createProduct(request);
        return ResponseEntity.ok(response.getProduct());
    }

    @GetMapping
    public ResponseEntity<List<Product>> listProducts() {
        ListProductsRequest request = ListProductsRequest.newBuilder().build();
        ListProductsResponse response = productServiceBlockingStub.listProducts(request);
        return ResponseEntity.ok(response.getProductsList());
    }

    // DTO for creating product
    public static class CreateProductRequestDto {
        private String name;
        private String description;
        private double price;
        private int quantity;

        // Getters and setters
        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public double getPrice() {
            return price;
        }

        public void setPrice(double price) {
            this.price = price;
        }

        public int getQuantity() {
            return quantity;
        }

        public void setQuantity(int quantity) {
            this.quantity = quantity;
        }
    }
}